package cn.virens.database.common;

import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

import cn.virens.exception.APIException;

public class TransactionExecute {
	private PlatformTransactionManager transactionManager;

	public TransactionExecute(PlatformTransactionManager transactionManager) {
		this.transactionManager = transactionManager;
	}

	public void read0(TransactionAccept consumer) {
		read(consumer);
	}

	public <T> T read(TransactionApply<T> function) {
		T result;

		DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
		definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		definition.setReadOnly(true);

		TransactionStatus status = transactionManager.getTransaction(definition);
		try {
			result = function.apply(status);

			transactionManager.commit(status);
		} catch (APIException ex) {
			transactionManager.rollback(status);

			throw new APIException(ex);
		} catch (Throwable ex) {
			transactionManager.rollback(status);

			throw new APIException(ex);
		}

		return result;
	}

	public void write0(TransactionAccept consumer) {
		write(consumer);
	}

	public <T> T write(TransactionApply<T> function) {
		T result;

		DefaultTransactionDefinition definition = new DefaultTransactionDefinition();
		definition.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		definition.setReadOnly(false);

		TransactionStatus status = transactionManager.getTransaction(definition);
		try {
			result = function.apply(status);

			transactionManager.commit(status);
		} catch (APIException ex) {
			transactionManager.rollback(status);

			throw new APIException(ex);
		} catch (Throwable ex) {
			transactionManager.rollback(status);

			throw new APIException(ex);
		}

		return result;
	}

	@FunctionalInterface
	public interface TransactionApply<R> {
		R apply(TransactionStatus t) throws Exception;
	}

	@FunctionalInterface
	public interface TransactionAccept extends TransactionApply<Object> {

		@Override
		default Object apply(TransactionStatus t) throws Exception {
			accept(t);

			return null;
		}

		void accept(TransactionStatus t) throws Exception;
	}
}
